package icu.bughub.app.app.viewmodel

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import icu.bughub.app.app.model.entity.UserInfoEntity
import icu.bughub.app.app.model.service.UserInfoManager
import icu.bughub.app.app.model.service.UserService
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import java.security.MessageDigest

class UserViewModel(context: Context) : ViewModel() {

    private val userInfoManager = UserInfoManager(context)

    var userInfo: UserInfoEntity? = null
        private set

    //是否已登录
    val logged: Boolean
        get() {
            return userInfo != null
        }

    init {
        //其实这里可以使用DataStore的对象存储，直接存储整个对象
        viewModelScope.launch {
            val userName = userInfoManager.userName.firstOrNull()
            userInfo = if (userName.isNullOrEmpty()) {
                null
            } else {
                UserInfoEntity(userName)
            }
        }
    }

    val userService = UserService.instance()

    /**
     * 登录
     */
    suspend fun login(onClose: () -> Unit = {}) {
        val params = mutableMapOf<String, Any>()
        params["userName"] = "18600000000"
        params["password"] = "e10adc3949ba59abbe56e057f20f883e"
        // params["password"] = md5("123456")
        val res = userService.login(params)
        if (res.code == 0) {
            //模拟网络请求数据回传
            // this.userInfo = UserInfoEntity("user001")
            this.userInfo = res.data
            viewModelScope.launch {
                userInfoManager.save(userInfo?.userName ?: "")
            }
        }

        onClose()
    }

    fun clear() {
        viewModelScope.launch {
            userInfoManager.clear() //清楚本地存储的数据
            userInfo = null
        }
    }

    fun md5(content: String): String {
        val hash = MessageDigest.getInstance("MD5").digest(content.toByteArray())
        val hex = StringBuilder(hash.size * 2)
        for (b in hash) {
            var str = Integer.toHexString(b.toInt())
            if (b < 0x10) {
                str = "0$str"
            } else {
                hex.append(str.substring(str.length - 2))
            }
        }
        return hex.toString()
    }

}